package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;

import com.py.credit.entity.ModelChoose;
import com.py.credit.entity.ModelDetail;
import com.py.credit.entity.ScoreRunningPc;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceModelChooseFieldsEnum;
import com.py.credit.entity.enums.ResourcePcDetailFieldsEnum;
import com.py.credit.entity.enums.ResourceScoreRunningPcFieldsEnum;
import com.py.credit.service.ScoreRunningService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

@RestController
@RequestMapping(value = "/scoreRunning")
public class ScoreRunningController {

    private final static String FRONT_TABLE_ID = "scoreRunning";

    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;

    @Autowired
    private ScoreRunningService scoreRunningService;

    @Value("${pdfJsPath}")
    private String pdfJsPath;

    @Value("${googlePath}")
    private String googlePath;

    @Value("${pdfPagePath}")

    private String pdfPagePath;

    /**
     * @api {get} /modelTest/getTableList.json 获取批次列表
     * @apiName getTableList
     * @apiVersion 0.0.1
     * @apiGroup 表规则管理
     * @apiParam {String} condition 查询条件(可选)
     * @apiParam {int} limit 每页展示条数 (必需)
     * @apiParam {int} page 当前页数 (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
     */
    @RequestMapping(value = "/getPcListByMainType.json")
    public RestServiceResult<List<Map<String, Object>>> getPcListByMainType(
            @RequestParam(value = "condition", required = false) String condition,
            @RequestParam(value = "mainType", required = false) String mainType, Page page,
            HttpServletRequest request) {

        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        String[] additionalColumns = {"id"};
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ResourceScoreRunningPcFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        try {
            List<Map<String, Object>> list = scoreRunningService.getByConditionForPage(showColumns, additionalColumns,
                    condition, page, mainType);
            if (!CollectionUtils.isEmpty(list)) {
                Set<Integer> userIds = new HashSet<Integer>(list.size());
                for (Map<String, Object> m : list) {
                    if (null != m && m.containsKey("cjr") && null != m.get("cjr")) {
                        userIds.add(Integer.parseInt(String.valueOf(m.get("cjr"))));
                    }
                }
                xypjRemoteBaseService.matchUserName(list, result, token, userIds, "cjr", "cjrName");
            }
            r = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), list);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常！");
        }
        return r;
    }

    /**
     * 获取批次初始化列
     *
     * @return
     */
    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(ResourceScoreRunningPcFieldsEnum.getOptionalColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    /**
     * 手动选择展示列
     *
     * @param columns
     * @return
     */
    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns) {
        RestServiceResult<String> r = new RestServiceResult<String>();
        try {
            MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(
                    ResourceScoreRunningPcFieldsEnum.getAdvancedConditionColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;

    }

    /**
     * @api {get} /modelTest/getTableList.json 按照批次查询企业得分列表
     * @apiName getTableList
     * @apiVersion 0.0.1
     * @apiGroup 表规则管理
     * @apiParam {String} condition 查询条件(可选)
     * @apiParam {int} limit 每页展示条数 (必需)
     * @apiParam {int} page 当前页数 (必需)
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {Object[]} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
     */
    @RequestMapping(value = "/getEnterPriseScoreByPcTableList.json")
    public RestServiceResult<List<ModelDetail>> getEnterPriseScoreByPcTableList(
            @RequestParam(value = "condition", required = false) String condition,
            @RequestParam(value = "pcId", required = true) String pcId, Page page, HttpServletRequest request) {

        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<ModelDetail>> result = new RestServiceResult<List<ModelDetail>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        String[] additionalColumns = {"id,pcId,reportStatus"};
        String[] configColumns = (String[]) MapCache.get(1 + "_" + FRONT_TABLE_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ResourcePcDetailFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
        RestServiceResult<List<ModelDetail>> r = new RestServiceResult<List<ModelDetail>>();
        try {
            List<ModelDetail> tableList = scoreRunningService.selectPcDetailByConditionForPage(showColumns,
                    additionalColumns, condition, page, pcId);
            r = new RestServiceResult<List<ModelDetail>>(page.getTotalCount(), tableList);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常！");
        }
        return r;
    }

    /**
     * 获取批次详情初始化列
     *
     * @return
     */
    @RequestMapping(value = "/getDetailOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getDetailOptionalColums() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(ResourcePcDetailFieldsEnum.getOptionalColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    /**
     * 手动选择批次详情展示列
     *
     * @param columns
     * @return
     */
    @RequestMapping(value = "/addDetailShowColunms.json")
    public RestServiceResult<String> addDetailShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns) {
        RestServiceResult<String> r = new RestServiceResult<String>();
        try {
            MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    /**
     * 获取批次详情高级查询
     *
     * @return
     */
    @RequestMapping(value = "/getDetailAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getDetailAdvancedConditionColumns() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(ResourcePcDetailFieldsEnum.getAdvancedConditionColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;

    }

    @RequestMapping(value = "/getModelListByMainType.json", method = RequestMethod.POST)
    @ApiOperation(value = "按照主体类型查询模型", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "condition", value = "查询条件", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "mainType", value = "主体类型", required = true)})
    public RestServiceResult<List<ModelChoose>> getModelListByMainType(
            @RequestParam(value = "condition", required = false) String condition,
            @RequestParam(value = "mainType", required = true) String mainType, Page page, HttpServletRequest request) {
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<ModelChoose>> result = new RestServiceResult<List<ModelChoose>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        String[] additionalColumns = {};
        String[] configColumns = (String[]) MapCache.get(1 + "_" + FRONT_TABLE_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ResourceModelChooseFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
        try {
            List<ModelChoose> tableList = scoreRunningService.getModelListByMainTypeForPage(showColumns,
                    additionalColumns, condition, page, mainType);
            result = new RestServiceResult<List<ModelChoose>>(page.getTotalCount(), tableList);
            result.setData(tableList);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("系统异常！");
        }

        return result;

    }

    /**
     * 获取模型初始化列
     *
     * @return
     */
    @RequestMapping(value = "/getModelOptionalColums.json", method = RequestMethod.POST)
    @ApiOperation(value = "获取模型初始化列", httpMethod = "POST", produces = "application/json")
    public RestServiceResult<List<OptionalColumn>> getModelOptionalColums(HttpServletRequest request) {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(ResourceModelChooseFieldsEnum.getOptionalColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    @RequestMapping(value = "/saveTask.do", method = RequestMethod.POST)
    @ApiOperation(value = "保存任务", httpMethod = "POST", produces = "application/json")
    @Transactional
    public RestServiceResult<Object> saveTask(@RequestParam(value = "frenquency", required = true) String frenquency,
                                              @RequestParam(value = "day", required = true) String day,
                                              @RequestParam(value = "executionType", required = true) String executionType,
                                              @RequestParam(value = "time", required = true) String time,
                                              @RequestParam(value = "nextTime", required = true) String nextTime,
                                              @RequestParam(value = "mainType", required = true) String mainType,
                                              @RequestParam(value = "modelId", required = true) String modelId,
                                              @RequestParam(value = "initIndexScore", required = true) String initIndexScore,
                                              HttpServletRequest request) {
        /*
         * String token = HttpServletHelper.getUserToken(request);
         * RestServiceResult<Object> result = new RestServiceResult<Object>();
         * //获取当前用户信息 RestServiceResult<SysUser> user =
         * xypjRemoteBaseService.getCurrentUser(token); SysUser userInfo = null; if
         * (RestServiceResult.CODE_SUCCESS == user.getCode()) { userInfo =
         * user.getData(); if (null == userInfo || userInfo.getId() <= 0) {
         * result.setCode(RestServiceResult.CODE_UNKNOW);
         * result.setMsg("系统异常，请稍后再试！");
         * ExceptionLogger.error("BatchLogController#getTableList",
         * "未获取到当前用户信息！"); return result; } } else {
         * result.setCode(user.getCode()); result.setMsg(user.getMsg()); return
         * result; }
         */
        String[] t = time.split(":");
        for (int i = 0; i < t.length; i++) {
            if (t[i].length() == 2 && t[i].startsWith("0")) {
                t[i] = t[i].substring(1);
            }
        }
        String cron = "";
        cron += t[2] + " " + t[1] + " " + t[0] + " ";
        if (frenquency.equals("1")) {
            cron += day + " * ?";
        } else if (frenquency.equals("2")) {
            cron += "? * ";
            if (day.equals("1")) {
                cron += "MON";
            } else if (day.equals("2")) {
                cron += "TUE";
            } else if (day.equals("3")) {
                cron += "WED";
            } else if (day.equals("4")) {
                cron += "THU";
            } else if (day.equals("5")) {
                cron += "FRI";
            } else if (day.equals("6")) {
                cron += "SAT";
            } else if (day.equals("7")) {
                cron += "SUN";
            }
        } else {
            cron += "* * ?";
        }
        String taskName = "";
        String menuId = "";
        String taskDesc = "";
        String taskUrl = "/scoreRunning/autoScore.do?mainType=" + mainType;
        if ("100000".equals(mainType)) {
            taskName = "法人库评分定时任务";
            menuId = "800";
            taskDesc = "法人库评分定时任务";
        } else if ("100001".equals(mainType)) {
            taskName = "自然人库评分定时任务";
            menuId = "800";
            taskDesc = "自然人法人库评分定时任务";
        } else if ("100002".equals(mainType)) {
            taskName = "非企业法人库评分定时任务";
            menuId = "800";
            taskDesc = "非企业法人库评分定时任务";

        }
        xypjRemoteBaseService.addTaskInfoForXypj(taskName, menuId, taskDesc, taskUrl, cron);
        scoreRunningService.addSch(modelId, initIndexScore, mainType, executionType, frenquency, day, time, nextTime);
        return new RestServiceResult<Object>();

    }

    @Transactional
    @RequestMapping(value = "/updateTaskStatus.do", method = RequestMethod.POST)
    @ApiOperation(value = "停止/启用任务", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "mainType", value = "主体类型", required = true)})
    public RestServiceResult<Object> updateTaskStatus(
            @RequestParam(value = "mainType", required = true) String mainType, HttpServletRequest request) {

        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        Map<String, String> m = scoreRunningService.selectSchInfoByMainType(mainType);
        String taskUrl = "/scoreRunning/autoScore.do?mainType=" + mainType;
        String status = m.get("status");
        if (StringUtils.isNoneBlank(status)) {
            if ("1".equals(status)) {
                status = "2";
            } else {
                status = "1";
            }
        }
        scoreRunningService.updateSchStatus(status, mainType);
        xypjRemoteBaseService.updateTaskStatusForXypj(status, "800", taskUrl);
        return result;

    }

    @RequestMapping(value = "/updatePcCallablility.do", method = RequestMethod.POST)
    @ApiOperation(value = "停止/启用批次", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "isCallable", value = "是否可调用", required = true)})
    public RestServiceResult<Object> updatePcCallablility(@RequestParam(value = "pcId", required = true) String pcId,
                                                          @RequestParam(value = "isCallable", required = true) String isCallable, HttpServletRequest request) {
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<Object> result = new RestServiceResult<Object>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        if (StringUtils.isNoneBlank(isCallable)) {
            if ("1".equals(isCallable)) {
                isCallable = "0";
            } else {
                isCallable = "1";
            }
        }
        scoreRunningService.updatePcCallablility(pcId, isCallable);
        return result;

    }

    @RequestMapping(value = "/autoScore.do")
    @ApiOperation(value = "自动算分", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "mainType", value = "主体类型", required = true)})
    public RestServiceResult<Object> autoScore(@RequestParam(value = "mainType", required = true) String mainType) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        try {
            ScoreRunningPc scoreRunningPc = new ScoreRunningPc();
            scoreRunningPc.setId(UuidUtil.getUUid());
            scoreRunningPc.setIsDel("1");
            scoreRunningPc.setMainType(mainType);
            scoreRunningPc.setStatus("2");
            scoreRunningPc.setIsCallable("1");
            scoreRunningPc.setReportStatus("0");
            List<String> tybms = scoreRunningService.getAllTybms();
            
            scoreRunningService.autoScore(scoreRunningPc, StringUtils.join(tybms, ","));
        } catch (Exception e) {
            result.setMsg(e.getMessage());
        }
        return result;

    }

    @RequestMapping(value = "/getScoreByEnterprise.json", method = RequestMethod.POST)
    @ApiOperation(value = "根据企业编码获取该企业的最新报告评分", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "qybm", value = "企业编码", required = true)})
    public RestServiceResult<String> getScoreByEnterprise(@RequestParam(value = "qybm", required = true) String qybm) {

        return new RestServiceResult<String>(new String());

    }

    @RequestMapping(value = "/viewScoreDetail.json", method = RequestMethod.POST)
    @ApiOperation(value = "查看得分明细", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "tybm", value = "企业统一编码", required = true)

    })
    public RestServiceResult<List<Map>> viewScoreDetail(@RequestParam(value = "pcId", required = true) String pcId,
                                                        @RequestParam(value = "tybm", required = true) String tybm, HttpServletRequest request) {

        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        return result;

    }

    @RequestMapping(value = "/buildReport.do", method = RequestMethod.POST)
    @ApiOperation(value = "一键生成报告", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "tybms", value = "企业统一编码列表", required = false)

    })
    public RestServiceResult<Object> buildReport(@RequestParam(value = "pcId", required = true) String pcId,
                                                 @RequestParam(value = "tybms", required = false) String tybms) {

        List<Map> list = new ArrayList<Map>();
        return new RestServiceResult<Object>();

    }

    @RequestMapping(value = "/previewReport.json", method = RequestMethod.POST)
    @ApiOperation(value = "预览报告", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "tybm", value = "企业统一编码", required = true)

    })
    public RestServiceResult<Object> previewReport(@RequestParam(value = "pcId", required = true) String pcId,
                                                   @RequestParam(value = "tybm", required = true) String tybm) {

        List<Map> list = new ArrayList<Map>();
        return new RestServiceResult<Object>();

    }

    @RequestMapping(value = "/selectSchInfoByMainType.json", method = RequestMethod.POST)
    public RestServiceResult<Map> selectSchInfoByMainType(
            @RequestParam(value = "mainType", required = true) String mainType, HttpServletRequest request) {
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<Map> result = new RestServiceResult<Map>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        Map<String, String> m = scoreRunningService.selectSchInfoByMainType(mainType);
        result.setData(m);
        return result;

    }

    @RequestMapping(value = "/selectScoreInfoByTybm.json", method = RequestMethod.POST)
    public RestServiceResult<Map> selectScoreInfoByTybm(
            @RequestParam(value = "modelId", required = true) String modelId,
            @RequestParam(value = "tybm", required = true) String tybm, HttpServletRequest request) {
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<Map> result = new RestServiceResult<Map>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        Map<String, String> m = scoreRunningService.selectScoreInfoByTybm(modelId, tybm);
        result.setData(m);
        return result;

    }
    
	@RequestMapping(value = "/export.json")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			  @RequestParam(value = "condition", required = false) String condition,
	            @RequestParam(value = "pcId", required = true) String pcId,
	            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,Page page,HttpServletResponse response, HttpServletRequest request)  {
		  String token = HttpServletHelper.getUserToken(request);
	        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
	        // 获取当前用户信息
	        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
	        SysUser userInfo = null;
	        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	            userInfo = user.getData();
	            if (null == userInfo || userInfo.getId() <= 0) {
	                result.setCode(RestServiceResult.CODE_UNKNOW);
	                result.setMsg("系统异常，请稍后再试！");
	                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
	                return result;
	            }
	        } else {
	            result.setCode(user.getCode());
	            result.setMsg(user.getMsg());
	            return result;
	        }
	        String[] additionalColumns = {"id,pcId,reportStatus"};
	        String[] configColumns = (String[]) MapCache.get(1 + "_" + FRONT_TABLE_ID);
	        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
	    	List<OptionalColumn> optionalColumns = ResourcePcDetailFieldsEnum.getOptionalColumns();
	        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
	        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
	        try {
	            List<Map<String, Object>> tableList = scoreRunningService.selectexportPcDetailByConditionForPage(showColumns,
	                    additionalColumns, condition, page, pcId);
	            r = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	        
			ExcelUtil.downloadExcel(response, tableList, "分级分类名单", "分级分类名单", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("分级分类名单导出异常，请稍后再试");
			return result;
		}
	}
	
	@RequestMapping(value = "/exportAll.json")
	public RestServiceResult<List<Map<String, Object>>> exportAll(
			  @RequestParam(value = "condition", required = false) String condition,
	            @RequestParam(value = "pcId", required = true) String pcId,
	            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,HttpServletResponse response, HttpServletRequest request)  {
		  String token = HttpServletHelper.getUserToken(request);
	        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
	        // 获取当前用户信息
	        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
	        SysUser userInfo = null;
	        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	            userInfo = user.getData();
	            if (null == userInfo || userInfo.getId() <= 0) {
	                result.setCode(RestServiceResult.CODE_UNKNOW);
	                result.setMsg("系统异常，请稍后再试！");
	                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
	                return result;
	            }
	        } else {
	            result.setCode(user.getCode());
	            result.setMsg(user.getMsg());
	            return result;
	        }
	        String[] additionalColumns = {"id,pcId,reportStatus"};
	        String[] configColumns = (String[]) MapCache.get(1 + "_" + FRONT_TABLE_ID);
	        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
	    	List<OptionalColumn> optionalColumns = ResourcePcDetailFieldsEnum.getOptionalColumns();
	        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
	        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
	        try {
	            List<Map<String, Object>> tableList = scoreRunningService.selectexportPcDetailByCondition(showColumns,
	                    additionalColumns, condition, pcId);
	          
	        
			ExcelUtil.downloadExcel(response, tableList, "分级分类名单", "分级分类名单", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("分级分类名单导出异常，请稍后再试");
			return result;
		}
	}
}
